package com.example.util;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author fanhang
 */
public class HttpUriBuilder {
    private final String path;
    private final Map<String, String> queryParams = new LinkedHashMap<>();

    private final Function<Map.Entry<String, String>, String> noEncode = i -> i.getKey() + "=" + i.getValue();
    private final Function<Map.Entry<String, String>, String> encode = i -> i.getKey() + "=" + URLEncoder.encode(i.getValue(), StandardCharsets.UTF_8);

    private HttpUriBuilder(String path) {
        this.path = path;
    }

    public static HttpUriBuilder fromPath(String path) {
        int index = path.indexOf('?');
        if (index != -1) {
            path = path.substring(0, index);
        }
        if (path.endsWith("/")) {
            path = path.substring(0, path.length() - 1);
        }
        return new HttpUriBuilder(path);
    }

    public HttpUriBuilder queryParam(String name, Object value) {
        if (value != null) {
            this.queryParam(name, value.toString());
        }
        return this;
    }

    public HttpUriBuilder queryParam(String name, String value) {
        if (value != null && !value.isBlank()) {
            this.queryParams.put(name, value);
        }
        return this;
    }

    public String build(String endpoint, boolean encoded) {
        return endpoint + path + "?" + this.queryParams.entrySet().stream().map(encoded ? encode : noEncode).collect(Collectors.joining("&"));
    }

}
